package com.yyplatform.admin.platform.file.controller;

import static com.yyplatform.admin.Constants.URL_PREFIX;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yyplatform.admin.infra.model.RestResponse;
import com.yyplatform.admin.platform.file.model.dto.SysFileDTO;
import com.yyplatform.admin.platform.file.model.dto.SysFileQueryDTO;
import com.yyplatform.admin.platform.file.service.SysFileService;
import com.yyplatform.admin.platform.file.service.SysFileUploadService;
import com.yyplatform.admin.platform.file.utils.FileUrlUtils;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-18
 */
@Slf4j
@Tag(name = "文件/文件管理")
@AllArgsConstructor
@RestController
@RequestMapping(URL_PREFIX + "/sys/file/")
public class SysFileController {
    private SysFileService sysFileService;
    private SysFileUploadService fileUploadService;


    @GetMapping("query")
    @Operation(summary = "查询")
    @RequiresPermissions("sys:file:query")
    public RestResponse<Page<SysFileDTO>> query(SysFileQueryDTO queryDTO, HttpServletRequest request) {

        log.debug("query dto = {}", queryDTO);

        Page<SysFileDTO> page = sysFileService.query(queryDTO);

        List<SysFileDTO> fileDTOList = page.getContent();
        fileDTOList.forEach(e -> {
            e.setUrl(FileUrlUtils.replaceUrl(e.getUrl(), request));
        });

        return RestResponse.ok(page);
    }

    @PostMapping("delete")
    @Operation(summary = "删除")
    @RequiresPermissions("sys:file:delete")
    public RestResponse<Void> delete(Long id) {
        log.debug("delete by id is {}", id);

        sysFileService.delete(id);
        return RestResponse.ok();
    }


    @PostMapping("uploadFile")
    @Operation(summary = "上传文件")
    @RequiresPermissions("sys:file:uploadFile")
    public RestResponse<String> uploadFile(MultipartFile file, HttpServletRequest request) {
        String fileUrl = fileUploadService.uploadFile(file);

        return RestResponse.ok(FileUrlUtils.replaceUrl(fileUrl, request));
    }


}
